package com.company.ems.controller;

import com.company.ems.dao.EmployeeDAOImpl;
import com.company.ems.model.Employee;
import com.company.ems.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/dashboard/employees")
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private EmployeeDAOImpl employeeDAO;
    private SimpleDateFormat dateFormat;

    @Override
    public void init() {
        employeeDAO = new EmployeeDAOImpl();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "list":
                listEmployees(request, response);
                break;
            case "view":
                viewEmployee(request, response);
                break;
            case "add":
                showAddForm(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "delete":
                deleteEmployee(request, response);
                break;
            case "search":
                searchEmployees(request, response);
                break;
            default:
                listEmployees(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) {
            response.sendRedirect("employees?action=list");
            return;
        }

        switch (action) {
            case "add":
                addEmployee(request, response);
                break;
            case "edit":
                updateEmployee(request, response);
                break;
            default:
                listEmployees(request, response);
        }
    }

    // 列出所有员工
    private void listEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Employee> employees = employeeDAO.getAllEmployees();
        request.setAttribute("employees", employees);
        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }

    // 查看员工详情
    private void viewEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.getEmployeeById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/view.jsp").forward(request, response);
        } else {
            response.sendRedirect("employees?action=list");
        }
    }

    // 显示添加员工表单
    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
    }

    // 添加员工
    private void addEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");

            Employee employee = new Employee();
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(new BigDecimal(request.getParameter("salary")));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            employee.setHireDate(dateFormat.parse(request.getParameter("hireDate")));
            employee.setCreatedBy(user.getId());

            employeeDAO.addEmployee(employee);
            response.sendRedirect("employees?action=list");
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误，请使用yyyy-MM-dd格式");
            request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
        }
    }

    // 显示编辑员工表单
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.getEmployeeById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        } else {
            response.sendRedirect("employees?action=list");
        }
    }

    // 更新员工信息
    private void updateEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int id = Integer.parseInt(request.getParameter("id"));

            Employee employee = new Employee();
            employee.setId(id);
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(new BigDecimal(request.getParameter("salary")));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            employee.setHireDate(dateFormat.parse(request.getParameter("hireDate")));

            employeeDAO.updateEmployee(employee);
            response.sendRedirect("employees?action=list");
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误，请使用yyyy-MM-dd格式");
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        }
    }

    // 删除员工
    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        employeeDAO.deleteEmployee(id);
        response.sendRedirect("employees?action=list");
    }

    // 搜索员工（可选功能）
    private void searchEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String department = request.getParameter("department");
        String position = request.getParameter("position");

        List<Employee> employees = employeeDAO.searchEmployees(name, department, position);
        request.setAttribute("employees", employees);
        request.setAttribute("searchParams", request.getParameterMap());
        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }
}